var express = require('express');
var pool = require('../mysql');
var router = express.Router();

/* GET login page. */
router.route('/')
  .get(function(req, res, next) {
    let name = req.cookies.user;
    pool.query(`select * from user where name = '${name}'`, function (err, result) {
      if(result){
        res.redirect('/index');
      }else{
        res.render('login', { title: 'login'});
      }
    });
  })
  .post(function(req, res, next) {
    let {account = '', password = ''} = req.body;
    pool.query(`select * from user where name = '${account}'`, function (err, result) {
      if(result){
        let _data = result[0] || [];
        if(password == _data.password){
          res.cookie('user',_data.name);
          res.redirect('/index');
        }else{
          res.send(`密码错误，二秒后返回登入页
            <script>
              setTimeout(() => {
                window.location.href='/login';
              }, 2000);
            </script>
          `);
        }
      }else{
        res.send(`账号错误，二秒后返回登入页
          <script>
            setTimeout(() => {
              window.location.href='/login';
            }, 2000);
          </script>
        `);
      }
    });
  });

  //退出登入
router.get('/exit', function(req, res, next) {
  res.clearCookie('user');``
  res.redirect('/login');
});

module.exports = router;